package message

import (
	"gomonitor-server/src/mylog"
	"gomonitor-server/src/tcp/types"
	"gomonitor-server/src/util"
	"net"
)

func (messageHandler *MessageHandler) ReceiveMessage(msgFrom byte, n int, buffer []byte, bufferPool *[]byte, conn net.Conn) bool {
	if n >= 14 {
		if util.BytesEqual(buffer[0:4], types.MsgHeaderBytes) && buffer[4] == msgFrom {
			msgLen := util.Bytes2Int(buffer[6 : 6+4])
			msgType := buffer[5]
			//remainingLen :=  msgLen+4
			totalLen := 14 + msgLen
			if uint32(n) < totalLen {
				//接收到的数据比实际长度要短，还需要读取
				usedData := buffer[:n]
				*bufferPool = append(*bufferPool, usedData...)
				mylog.Logger.Warningf("消息类型:%d,需要的包长度是:%d，实际长度:%d，断包", msgType, totalLen, n)
				return false
			} else if uint32(n) > totalLen {
				//接收到的数据比实际长度要长，要把多余的放到缓冲区
				unusedData := buffer[totalLen:n]
				*bufferPool = append(*bufferPool, unusedData...)
			}
			msgDataStartIndex := 10
			msgDataEndIndex := 10 + msgLen
			msgData := buffer[msgDataStartIndex:msgDataEndIndex]
			msgSum := util.Bytes2Int(buffer[msgDataEndIndex:(msgDataEndIndex + 4)])
			msgCheckSum := util.CalculateChecksum(msgData)
			if msgSum == msgCheckSum {
				mylog.Logger.Debugf("接收到客户端:%s 的数据，类型:%d,数据长度:%d,数据包总长度:%d,len数据包长度:%d", conn.RemoteAddr().String(), msgType, msgLen, n, len(buffer))
				//相等。可以读取
				MessageProcess(messageHandler, msgType, msgData, conn)
			} else {
				mylog.Logger.Errorf("客户端:%s数据和:%d与数据校验和%d不相等丢弃数据....", conn.RemoteAddr().String(), msgSum, msgCheckSum)
			}
			return true
		} else {
			//断包了
			mylog.Logger.Errorf("接收到消息头格式错误,内容:%s,msgFrom:%d", buffer[0:4], buffer[4])
			//接收到的数据比实际长度要短，还需要读取
			usedData := buffer[:n]
			*bufferPool = append(*bufferPool, usedData...)
			return false
		}
	} else {
		//接收到的数据比实际长度要短，还需要读取
		usedData := buffer[:n]
		*bufferPool = append(*bufferPool, usedData...)
		mylog.Logger.Warningf("消息头长度不够，实际接收到的长度是:%d", n)
		return false
	}
}
